﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace JoinBox.JoinBox_Code.WPF.多文档标签.View
{
    public class ControlDragDrop
    {
        public delegate void DelegateChangControlDragDrop(object sender, DragEventArgs e);
        DelegateChangControlDragDrop dcc;

        /// <summary>
        /// 将控件设置可拖入输入
        /// </summary>
        /// <param name="control"></param>
        /// <param name="dccdd">委托</param>
        public ControlDragDrop(Control control, DelegateChangControlDragDrop dccdd)
        {
            dcc = dccdd;
            var a = control.GetType();
            var b = a.GetProperty("AllowDrop");
            if (b == null)
            {
                throw new Exception("DragTextBox::此控件不存在AllowDrop属性");
            }
            control.AllowDrop = true;
            control.DragEnter += Co_DragEnter;
            control.Drop += Co_DragDrop;
        }

        private void Co_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Link;

                //反射写法
                var con = sender.GetType();
                if (con != null)
                {
                    var ss = con.GetProperty("Cursor");
                    if (ss == null)
                    {
                        throw new Exception("DragTextBox,Co_DragEnter::此控件不存在Cursor属性");
                    }
                    else
                    {
                        ss.SetValue(sender, System.Windows.Input.Cursors.Arrow, null);
                    }
                }
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private void Co_DragDrop(object sender, DragEventArgs e)
        {
            //反射写法
            var con = sender.GetType();
            if (con != null)
            {
                dcc(sender, e);
                //还原鼠标
                var ss = con.GetProperty("Cursor");
                if (ss == null)
                {
                    throw new Exception("DragTextBox,Co_DragDrop::此控件不存在Cursor属性");
                }
                else
                {
                    ss.SetValue(sender, System.Windows.Input.Cursors.IBeam, null);
                }
            }
        }
    }
}
